<?php
  defined('_JEXEC') or die();
  jimport('joomla.application.component.model');
  
  class BaseModel extends JModel 
  {  
    var $_id         = null;
    var $_orderBy    = null;
    var $_attributes = null;
    var $_data       = null;
    var $_total      = null;
    var $_pagination = null;
    var $_default_col= 'id';
    
    var $_sql        = null;
    
    function __construct()
    {
      parent::__construct();
   
      global $mainframe;
   
      $filter_order     = $mainframe->getUserStateFromRequest($this->_name . 'filter_order', 'filter_order', $this->_default_col, 'cmd');
      $filter_order_Dir = $mainframe->getUserStateFromRequest($this->_name . 'filter_order_Dir', 'filter_order_Dir', 'asc', 'word');
      
      $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
      $limitstart = JRequest::getVar('limitstart', 0, '', 'int');

      $this->setState($this->_name . 'filter_order', $filter_order);
      $this->setState($this->_name . 'filter_order_Dir', $filter_order_Dir);
      
      // In case limit has been changed, adjust it
      $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
     
      $this->setState('limit', $limit);
      $this->setState('limitstart', $limitstart);
    }
    
    function _orderBy()
    {
      global $mainframe;

      $orderby = '';
      $filter_order     = $this->getState($this->_name . 'filter_order');
      $filter_order_Dir = $this->getState($this->_name . 'filter_order_Dir');

      if(!empty($filter_order) && !empty($filter_order_Dir))
      {
        $orderby = ' ORDER BY '.$filter_order.' '.$filter_order_Dir;
      }

      return $orderby;
    }
    
    function get($id = null, $use_orderBy = false, $attributes = array())
    {
      $db    = $this->getDBO();
      $where = null;
      if(is_array($id) && !empty($id))
        $where = ' WHERE id in (' . implode(',',$id) . ')';
      elseif($id)
        $where = ' WHERE id = ' . $id;
    
      if(empty($attributes))
        $sql = 'SELECT * '; 
      else
        $sql = 'SELECT '.implode(',',$attributes).' ';
        
      $sql .= 'FROM ' . $this->_table . 
          $where;
      
      if($use_orderBy)
        $sql .= $this->_orderBy();
        
      $db->setQuery($sql);
      
      $result = $db->loadObjectList();
      
      if ($result === null)
        JError::raiseError(500, 'Error reading db' .  $this->getDBO()->getErrorMsg());
    
      if((count($result) > 0) && (is_array($id) || is_null($id)))
        return $result;
      elseif(count($result) > 0 && !empty($id))
        return $result[0];
      else
        return null;
    }
    
    function save($data)
    {
      $row =& $this->getTable($this->_name);            
           
      if (!$row->bind($data)) 
      {
        JError::raiseError(500, 'Error binding data');              
      }     
       
      if (!$row->check()) 
      {
        JError::raiseError(500, 'Invalid data');                           
      }
       
            if (!$row->store()) 
      {
        $errorMessage = $row->getError();
        JError::raiseError(500, 'Error binding data: '.$errorMessage);                           
      }
      
      return $row;
    }    
    
    function delete($ids)
    {
      $query = "DELETE FROM " . $this->_table . " WHERE id IN (" . implode(',', $ids) . ")";
      $db = $this->getDBO();
            $db->setQuery($query);
            if (!$db->query())
      {
                $errorMessage = $this->getDBO()->getErrorMsg();
                JError::raiseError(500, 'Error deleting: '.$errorMessage);  
            }         
    }
    
    function publish($ids, $publish = 1)
    {
      $query = "UPDATE " . $this->_table . " SET published = " . $publish . " WHERE id IN (" . implode(',', $ids) . ")";
      $db = $this->getDBO();
            $db->setQuery($query);
            if (!$db->query())
      {
                $errorMessage = $this->getDBO()->getErrorMsg();
                JError::raiseError(500, 'Error updating: '.$errorMessage);  
            }       
    }
    
    function getListData() 
    {
      // if data hasn't already been obtained, load it
      if (empty($this->_data)) {
        $this->_orderBy = true;
        $query  = $this->_buildQuery();
        $this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));  
      }
      return $this->_data;
    }
    
    function getTotal()
    {
      // Load the content if it doesn't already exist
      if (empty($this->_total)) {
        $query = $this->_buildQuery();
        $this->_total = $this->_getListCount($query);  
      }
      return $this->_total;
    }
    
    function getPagination()
    {
      // Load the content if it doesn't already exist
      if (empty($this->_pagination)) {
        jimport('joomla.html.pagination');
        $this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
      }
      return $this->_pagination;
    }

    /* PARAMS: override attrs and order by*/
    function _buildQuery(){
      
      $sql   = null;
      
      if(!$this->_sql){
        $where = null;
        if($this->_id)
          $where = ' WHERE id = ' . $id;
        
        if(empty($this->_attributes))
          $sql = 'SELECT * '; 
        else
          $sql = 'SELECT '.implode(',',$this->_attributes).' ';
          
        $sql .= 'FROM ' . $this->_table . 
            $where;
      }
      else
        $sql = $this->_sql;
      
      if($this->_orderBy)
        $sql .= $this->_orderBy();
        
      return $sql;
    }

	function exist($id){
	
	  $sql = "SELECT count(*) FROM " . $this->_table .
	         " WHERE id=$id";
	  $db    = $this->getDBO();
      $db->setQuery($sql);
      $result = ($db->loadResult() ? true : false);
	  return $result;
    }
    
    protected function _get($sql, $object_only = false)
    {
      $db    = $this->getDBO();
      $db->setQuery($sql);
      
      $result = $db->loadObjectList();
     
      if ($result === null)
        JError::raiseError(500, 'Error reading db' .  $this->getDBO()->getErrorMsg());

      if(count($result) > 0 && $object_only)
        return $result[0];
      elseif(count($result) > 0)
        return $result;
      else
        return null;
    }
  }
?>